package com.xinenhua.businessserver.house;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator;
import com.bigkoo.convenientbanner.holder.Holder;
import com.bigkoo.convenientbanner.listener.OnItemClickListener;
import com.githang.statusbar.StatusBarCompat;
import com.google.gson.Gson;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.oasis.oasislib.base.BaseFragmentActivity;
import com.oasis.oasislib.utils.DialogUtils;
import com.oasis.oasislib.utils.LogUtil;
import com.oasis.oasislib.utils.ToastUtils;
import com.xinenhua.businessserver.Const;
import com.xinenhua.businessserver.R;
import com.xinenhua.businessserver.contract.ContractDetail;
import com.xinenhua.businessserver.http.BaseHttp;
import com.xinenhua.businessserver.personal.subscribe.HeTong;
import com.xinenhua.businessserver.personal.subscribe.Wuye;

import org.apache.commons.lang3.StringUtils;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

import co.lujun.androidtagview.TagContainerLayout;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * 房源详情
 */
@ContentView(R.layout.housedetail)
public class HouseDetail extends BaseFragmentActivity implements OnItemClickListener {

    protected ImageLoader imageLoader;

    private List<String> networkImages;

    @ViewInject(R.id.convenientBanner)
    private ConvenientBanner convenientBanner;

    @ViewInject(R.id.tagcontainerLayout)
    private TagContainerLayout mTagContainerLayout;

    //房源id
    String houseid = "";

    //房源详情pojo
    HouseDetailPojo detail=null;

    //房号
    @ViewInject(R.id.fanghao)
    TextView fanghao;

    //宽带
    @ViewInject(R.id.kuandai)
    TextView kuandai;

    //物业费
    @ViewInject(R.id.wuyefei)
    TextView wuyefei;

    //门禁
    @ViewInject(R.id.menjin)
    TextView menjin;

    //
    @ViewInject(R.id.fuhuafuwu)
    TextView fuhuafuwu;
    //水电
    @ViewInject(R.id.shuidian)
    TextView shuidian;
    //自来水
    @ViewInject(R.id.szilaishui)
    TextView szilaishui;
    //注册押金
    @ViewInject(R.id.zhuceyajin)
    TextView zhuceyajin;
    //z中水
    @ViewInject(R.id.zhongshui)
    TextView zhongshui;

    @ViewInject(R.id.qita1)
    TextView qita1;


    //电费
    @ViewInject(R.id.dianfei)
    TextView dianfei;

    @ViewInject(R.id.qita2)
    TextView qita2;

    //公共网络
    @ViewInject(R.id.gonggong)
    TextView gonggong;


    @ViewInject(R.id.qita3)
    TextView qita3;

    //能源
    @ViewInject(R.id.nengyuan)
    TextView nengyuan;

    //开发商
    @ViewInject(R.id.kaifashang)
    TextView kaifashang;

    //采暖
    @ViewInject(R.id.cainuan)
    TextView cainuan;

    //物业管理公司
    @ViewInject(R.id.wuyeguanli)
    TextView wuyeguanli;

    //其他
    @ViewInject(R.id.qita)
    TextView qita;

    //标题
    @ViewInject(R.id.title)
    TextView title;

    //租金
    @ViewInject(R.id.rent)
    TextView rent;

    //平米每天
    @ViewInject(R.id.pingmimeitian)
    TextView pingmimeitian;

    //发布时间
    @ViewInject(R.id.fabushijian)
    TextView fabushijian;


    //大厦名
    @ViewInject(R.id.buildname)
    TextView buildname;

    //地址
    @ViewInject(R.id.dizhi)
    TextView dizhi;

    //后退
    @ViewInject(R.id.warpper_message)
    RelativeLayout warpper_message;

    //刷新图片
    @ViewInject(R.id.refreshimg)
    ImageView refreshimg;


    //生成合同
    @ViewInject(R.id.generate)
    RelativeLayout generate ;

    //查看支付凭证
    @ViewInject(R.id.showPay)
    RelativeLayout showPay ;

    //生成物业交割单
    @ViewInject(R.id.wuye)
    RelativeLayout wuye ;

    @ViewInject(R.id.wuye_show)
    TextView wue_show;

    @ViewInject(R.id.showCustomerInfo)
    Button showCustomerInfo;

    @Override
    protected void start() {
        super.start();

        findViewById(R.id.warpper_message).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        actionBar.hide();
        StatusBarCompat.setStatusBarColor(this, getResources().getColor(R.color.app_green));

        imageLoader = ImageLoader.getInstance();
        imageLoader.init(ImageLoaderConfiguration.createDefault(this));

        houseid = getIntent().getStringExtra("id");
        LogUtil.e(TAG,"houseid---"+houseid);

        warpper_message.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        refreshimg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                LogUtil.e(TAG,"刷新----------");
                getData();
            }
        });

    }

    @Override
    protected void onStart() {
        super.onStart();
        getData();
    }



    @Override
    public void onItemClick(int i) {

    }

    Dialog dialog ;

    public void getData(){

        dialog = DialogUtils.createLoadingDialog(context);
        dialog.show();

        HashMap<String,String> map = new HashMap<>() ;
        map.put("house_id",houseid);

        Call call = BaseHttp.getCallWithUrlAndData(Const.adminhousedetail,map);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                showMsg("Fail");
                dialog.dismiss();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String rr = new String(response.body().string());
                LogUtil.e(TAG,"房源详情--"+rr);
                int result = BaseHttp.preResult(rr);
                if(result==BaseHttp.DATA_OK){
                    String s = BaseHttp.getJsonDataAsString(rr);
                    System.out.println("String--"+s);
                    Gson gson = new Gson();
                    detail = gson.fromJson(s, HouseDetailPojo.class) ;
                    System.out.println("------------------------------------------");

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            //渲染页面
                            show();
                        }
                    });
                }else {
                    showMsg(BaseHttp.getJsonMsg(rr));
                }

                dialog.dismiss();

            }
        });
    }

    private void show() {

        generate.setBackgroundColor(getResources().getColor(R.color.app_green));
        generate.setClickable(true);

        showPay.setBackgroundColor(getResources().getColor(R.color.app_green));
        showPay.setClickable(true);

        wuye.setBackgroundColor(getResources().getColor(R.color.app_green));
        wuye.setClickable(true);

        generate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                LogUtil.e(TAG,"生成合同");
                Intent openWelcomeActivityIntent=new Intent();
                Bundle bundle=new Bundle();
                bundle.putString("house_id",detail.getId()+"");
                bundle.putString("yuyue_id","");
                openWelcomeActivityIntent.putExtras(bundle);
                openWelcomeActivityIntent.setClass(context, HeTong.class);
                startActivity(openWelcomeActivityIntent);
            }
        });

        showPay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                LogUtil.e(TAG,"查看支付凭证");
                Intent openWelcomeActivityIntent=new Intent();
                Bundle bundle=new Bundle();
                bundle.putString("ding",detail.getDingdanhao()+"");
                openWelcomeActivityIntent.putExtras(bundle);
                openWelcomeActivityIntent.setClass(context, ContractDetail.class);
                startActivity(openWelcomeActivityIntent);
            }
        });

        wuye.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                LogUtil.e(TAG,"生成物业交割单");
                Intent openWelcomeActivityIntent=new Intent();
                Bundle bundle=new Bundle();
                bundle.putString("id",detail.getDingdanhao());
                openWelcomeActivityIntent.putExtras(bundle);
                openWelcomeActivityIntent.setClass(context, Wuye.class);
                startActivity(openWelcomeActivityIntent);

            }
        });


        int house_status = detail.getHouse_status();
        int wuye_status = detail.getWuye_status() ;

        switch (house_status){
            case 1:
                //生成合同 不能点击   查看支付凭证 可以点击
                generate.setBackgroundColor(getResources().getColor(R.color.gray_line));
                generate.setClickable(false);

                showPay.setBackgroundColor(getResources().getColor(R.color.app_green));
                showPay.setClickable(true);

                if(wuye_status==0){
                    //物业交割单 还没生成  所以可以点击
                    wuye.setBackgroundColor(getResources().getColor(R.color.app_green));
                    wuye.setClickable(true);
                }
                if(wuye_status==1){
                    //物业交割单生成了 所以就不能点击了
                    wue_show.setText("已生成交割单");

                    wuye.setBackgroundColor(getResources().getColor(R.color.gray_line));
                    wuye.setClickable(false);
                }

                break;
            case 0:

                //0   没合同  可以生成合同       （ 查看支付凭证 和 物业交割单   不能点击   生成合同可以点击  ）

                showPay.setBackgroundColor(getResources().getColor(R.color.gray_line));
                showPay.setClickable(false);

                wuye.setBackgroundColor(getResources().getColor(R.color.gray_line));
                wuye.setClickable(false);

                break;
        }


        /*-----------------------------------*/


        rent.setText(detail.getRent()+"");
        //pingmimeitian.setText(detail.ge);

        title.setText(detail.getTitle());

        dizhi.setText(detail.getAddress());
        buildname.setText(detail.getBuild_name());

        fabushijian.setText("发布时间："+detail.getCreate_time());

        fanghao.setText("房号："+detail.getHouse_num());
        kuandai.setText("宽带："+detail.getKuandai());
        wuyefei.setText("物业管理费："+detail.getWuyeguanlifei());
        menjin.setText("门禁/钥匙/指纹："+detail.getMenjinyajin());

        fuhuafuwu.setText("孵化服务费："+detail.getFuhuafuwufei());
        shuidian.setText("水/电/IC卡："+detail.getShuidiankayajin());

        szilaishui.setText("生活自来水："+detail.getShenghuozilaishui());
        zhuceyajin.setText("注册押金："+detail.getZhuceyajin());

        zhongshui.setText("中水："+detail.getZhongshui());
        qita1.setText("其他（1）："+detail.getQita_1());

        dianfei.setText("电费："+detail.getDianfei());
        qita2.setText("其他（2）："+detail.getQita_2());

        gonggong.setText("公共网络："+detail.getGonggongwangluo());
        qita3.setText("其他（3）："+detail.getQita_3());

        nengyuan.setText("能源/超时能源："+detail.getNengyuan());
        kaifashang.setText("开发商："+detail.getKaifashang());

        cainuan.setText("采暖费："+detail.getCainuanfei());
        wuyeguanli.setText("物业管理公司:"+detail.getWuyeguanligongsi());

        qita.setText("其他："+detail.getQitayajin());

        final String hetongid = String.valueOf(detail.getHetong_id()) ;
        if(StringUtils.isBlank(hetongid)||"0".equals(hetongid)){

            showCustomerInfo.setVisibility(View.INVISIBLE);
            showCustomerInfo.setOnClickListener(null);
        }else {
            showCustomerInfo.setVisibility(View.VISIBLE);
            showCustomerInfo.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent openWelcomeActivityIntent=new Intent();
                    Bundle bundle=new Bundle();
                    bundle.putString("id",hetongid);
                    openWelcomeActivityIntent.putExtras(bundle);
                    openWelcomeActivityIntent.setClass(context, com.xinenhua.businessserver.entity.EntityCustomerInfo.class);
                    startActivity(openWelcomeActivityIntent);
                }
            });

        }


        //标签
        if(detail.getTag()!=null&&!"".equals(detail.getTag())){
            String[] ssss = detail.getTag().split(",");
            mTagContainerLayout.setTags(ssss);
        }
        //图片
        if(detail.getImage()!=null&&detail.getImage().size()>0){
            //网络加载例子
            networkImages = detail.getImage();
            convenientBanner.setPages(new CBViewHolderCreator<NetworkImageHolderView>(){

                @Override
                public NetworkImageHolderView createHolder() {
                    return new NetworkImageHolderView();
                }
            }, networkImages)
                    //设置指示器是否可见
                    .setPointViewVisible(true)
                    //设置自动切换（同时设置了切换时间间隔）
                    .startTurning(2000)
                    //设置两个点图片作为翻页指示器，不设置则没有指示器，可以根据自己需求自行配合自己的指示器,不需要圆点指示器可用不设
                    //.setPageIndicator(new int[]{R.drawable.ic_page_indicator, R.drawable.ic_page_indicator_focused})
                    //设置指示器的方向（左、中、右）
                    .setPageIndicatorAlign(ConvenientBanner.PageIndicatorAlign.ALIGN_PARENT_RIGHT)
                    //设置点击监听事件
                    .setOnItemClickListener(HouseDetail.this)
                    //设置手动影响（设置了该项无法手动切换）
                    .setManualPageable(true);
        }
    }

    class NetworkImageHolderView implements Holder<String> {//String为传入的数据类型，可以更改为其他
        private ImageView imageView;
        @Override
        public View createView(Context context) {
            //你可以通过layout文件来创建，也可以像我一样用代码创建，不一定是Image，任何控件都可以进行翻页
            imageView = new ImageView(context);
            imageView.setScaleType(ImageView.ScaleType.FIT_XY);
            return imageView;
            //view = LayoutInflater.from(context).inflate(R.layout.banner_item, null, false);
            // return view;
        }

        @Override
        public void UpdateUI(Context context,int position, String data) {
            //imageView.setImageResource(R.drawable.);
            ImageLoader.getInstance().displayImage(data,imageView);
        }
    }
}
